package com.hellobike.haxing.modules.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.product.entity.Sku;
import com.hellobike.haxing.modules.product.entity.Spu;
import com.hellobike.haxing.modules.product.service.ISkuService;
import com.hellobike.haxing.modules.product.service.ISpuService;
import com.hellobike.haxing.modules.wms.dto.DeliveryOrderBoxDto;
import com.hellobike.haxing.modules.wms.entity.Container;
import com.hellobike.haxing.modules.wms.entity.DeliveryOrderBox;
import com.hellobike.haxing.modules.wms.entity.DeliveryOrderHeader;
import com.hellobike.haxing.modules.wms.enums.ContainerStatusEnum;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsDeliveryFacade;
import com.hellobike.haxing.modules.wms.service.IContainerService;
import com.hellobike.haxing.modules.wms.service.IDeliveryOrderBoxService;
import com.hellobike.haxing.modules.wms.service.IDeliveryOrderHeaderService;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
* @Description: t_wms_container
* @Author: haxing-boot
* @Date:   2020-01-15
* @Version: V1.0
*/
@RestController
@RequestMapping("/wms/container")
@Slf4j
public class ContainerController extends WmsBaseController<Container, IContainerService> {
   @Autowired
   private IContainerService containerService;

   /**
    * 分页列表查询
    *
    * @param container
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "t_wms_container-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(Container container,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       container.setWarehouseId(getWarehouseId());
       QueryWrapper<Container> queryWrapper = QueryGenerator.initQueryWrapper(container, req.getParameterMap());
       Page<Container> page = new Page<Container>(pageNo, pageSize);
       IPage<Container> pageList = containerService.page(page, queryWrapper);
       return Result.ok(pageList);
   }

   /**
    *   添加
    *
    * @param container
    * @return
    */
   @AutoLog(value = "t_wms_container-添加",operateType=2)
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody Container container) throws WmsServiceException {
       String containerCode = container.getContainerCode();
       Container code = containerService.getByCode(containerCode, getWarehouseId());
       if (code != null) {
           throw new WmsServiceException("该编码已被占用");
       }
       container.setWarehouseId(getWarehouseId());
       containerService.save(container);
       return Result.ok("添加成功！");
   }

   /**
    *  编辑
    *
    * @param container
    * @return
    */
   @AutoLog(value = "t_wms_container-编辑",operateType=3)
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody Container container) throws WmsServiceException {
       Container container1 = containerService.getById(container.getId());
       if(!container1.getContainerCode().equals(container.getContainerCode())){
           Container code = containerService.getByCode(container.getContainerCode(), getWarehouseId());
           if (code != null) {
               throw new WmsServiceException("该编码已被占用");
           }
       }
       containerService.updateById(container);
       return Result.ok("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "t_wms_container-删除",operateType=4)
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) Long id) throws WmsServiceException {
       Container container = containerService.getById(id);
       if(!ContainerStatusEnum.FREE.getValue().equals(container.getContainerStatus()) && !ContainerStatusEnum.STOP_USING.getValue().equals(container.getContainerStatus())){
           throw new WmsServiceException("使用状态不能删除");
       }
       containerService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "t_wms_container-批量删除",operateType=4)
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.containerService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       Container container = containerService.getById(id);
       if(container==null) {
           return Result.error("未找到对应数据");
       }
       return Result.ok(container);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param container
   */
   @AutoLog(value = "t_wms_container-导出excel",operateType=6)
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, Container container) {
       return super.exportXls(request, container, Container.class, "t_wms_container");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @AutoLog(value = "t_wms_container-导入excel",operateType=5)
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, Container.class);
   }

   @Autowired
   private IDeliveryOrderHeaderService deliveryOrderHeaderService;
   @Autowired
   private IDeliveryOrderBoxService deliveryOrderBoxService;
   @Autowired
   private ISkuService skuService;
   @Autowired
   private ISpuService spuService;
   @Autowired
   private WmsDeliveryFacade wmsDeliveryFacade;


    @PostMapping(value = "/curDetail")
    public Result<?> curDetail(@RequestBody Container param) throws WmsServiceException {
        Container container = containerService.getById(param.getId());
        if (container == null) {
            throw new WmsServiceException("容器不存在");
        }
        Map<String,Object> result = new HashMap<>();
        List<DeliveryOrderBoxDto> detail = new ArrayList<>();
        if (container.getCurDocId() != null) {
            DeliveryOrderHeader orderHeader = deliveryOrderHeaderService.getById(container.getCurDocId());
            if (orderHeader == null) {
                throw new WmsServiceException("订单不存在");
            }
            result.put("curDocNo",orderHeader.getOrderCode());
            List<DeliveryOrderBox> orderBoxes = deliveryOrderBoxService.getByOrderHeaderId(orderHeader.getId());
            if(ListUtil.isNotEmpty(orderBoxes)){
                for (DeliveryOrderBox orderBox : orderBoxes) {
                    if(container.getId().equals(orderBox.getBoxId())){
                        DeliveryOrderBoxDto dto = new DeliveryOrderBoxDto();
                        BeanUtils.copyProperties(orderBox, dto);
                        Sku sku = skuService.getById(orderBox.getSkuId());
                        if (sku != null) {
                            Spu spu = spuService.getById(sku.getSpuId());
                            dto.setBarCode(sku.getBarcode());
                            dto.setSkuCode(sku.getSkuCode());
                            dto.setSpuCode(spu.getSpuCode());
                            dto.setSpuName(spu.getSpuName());
                            dto.setDimensionValues(sku.getDimensionValues());
                        }
                        detail.add(dto);
                    }
                }
            }
            result.put("detail",detail);
        }else {
            result.put("curDocNo","");
            result.put("detail",detail);

        }
        return Result.ok(result);
    }

    @AutoLog(value = "t_wms_container-解绑",operateType=2)
    @PostMapping(value = "/free")
    public Result<?> free(@RequestBody Container param) throws WmsServiceException {
        wmsDeliveryFacade.freeContainer(param.getId(),getWarehouseId(),getSysUserId());
        return Result.ok("解绑成功！");
    }

}
